//
// Created by 31951 on 2020/11/5.
//

#include "PartialShot.h"

PartialShot::PartialShot(QWidget *parent)
        : QWidget(parent) {
    this->setCursor(Qt::CrossCursor);
}

void PartialShot::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        mouse_pressed = true;
        start_pos = event->pos();
    }
}

void PartialShot::mouseReleaseEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        mouse_pressed = false;
    }
}

void PartialShot::mouseMoveEvent(QMouseEvent *event) {
    if (mouse_pressed) {
        end_pos = event->pos();
        update();
    }
}

void PartialShot::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    QPen pen(Qt::red, 1);
    painter.setPen(pen);


    // 设置 rectF
    int lx = start_pos.x() < end_pos.x() ? start_pos.x() : end_pos.x();
    int ly = start_pos.y() < end_pos.y() ? start_pos.y() : end_pos.y();
    int w = qAbs(start_pos.x() - end_pos.x());
    int h = qAbs(start_pos.y() - end_pos.y());
    save_rect.setRect(lx, ly, w, h);


    if (start_pos.rx() != -1 && (start_pos.ry() - end_pos.ry() != 0)) {
        // 防止第一次就画截图， 高度 > 0 时才画
        painter.drawPixmap(save_rect, screen_image, save_rect);
        painter.drawRect(save_rect);
    }
}

void PartialShot::showEvent(QShowEvent *event) {
    //设置透明度实现模糊背景
    setWindowOpacity(0.7);
}

void PartialShot::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
        case Qt::Key_Escape:
            this->close();
            break;
        case Qt::Key_Enter: {
            QGuiApplication::clipboard()->setPixmap(screen_image.copy(save_rect));
            auto file_name = QFileDialog::getSaveFileName(
                    nullptr,
                    tr("保存文件")
            );
            if (!file_name.isEmpty())
                screen_image.copy(save_rect).save(file_name, "png");
            this->close();
            break;
        }
        default:
            event->ignore();
    }
}

void PartialShot::setScreenImage(const QPixmap &screenImage) {
    screen_image = screenImage;
}
